﻿@using XRM.Security.DataAccess.Enums
@using XRM.Security.DataAccess.Helpers
@using XRM.Security.WebUI.MvcHelpers
@using EnumHelper = XRM.Sag.Utils.Helpers.EnumHelper
@model XRM.Security.WebUI.Models.CertRegister.CertRegisterModel
@{
    ViewBag.Title = "Информация о сертификате";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@Html.Partial("ReturnLinkPartial", new Tuple<string, string>(Model.ReturnUrl, "Вернуться к списку сертификатов"))

<div>
    @using (Html.BeginForm("Edit", "CertRegister", FormMethod.Post, new { @class = "form-horizontal form-horizontal-2" }))
    {
        @Html.AntiForgeryToken()

        const string inputCss = "form-control";
        const string divCss = "col-sm-4";

        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.IsFromUser)
        @Html.HiddenFor(m => m.ReturnUrl)
        @Html.HiddenFor(m => m.DataId)

        @Html.DialogFormButton(new DialogButtonOptions()
           {
               Text = "Создать пользователя",
               ContentUrl = Url.Action("AddUserRegisterDialog", "UserRegister"),
               Width = "800",
               Id = "dlgAddUserRegisterDialog",
               ButtonCss = "btn btn-large btn-primary hidden",
               OnSuccess = "GetSelectedUser",
               ButtonId = "btnAddUser"
           })

        @Html.DialogFormButton(new DialogButtonOptions()
           {
               Text = "Выбрать пользователя",
               ContentUrl = Url.Action("ADUsersDialog", "UserRegister"),
               Width = "800",
               Id = "dlgADUsersDialog",
               ButtonCss = "btn btn-large btn-primary hidden",
               OnSuccess = "GetSelectedUser",
               ButtonId = "btnSelectUser",
               OnOpen = "InitSearchUsersDialog"
           })
                
            <div class="form-group">
                @Html.LabelFor(m => m.IdentityCenterName, new { @class = "control-label" })
                <div class="@divCss control-text">
                    @Model.IdentityCenterName
                    @Html.HiddenFor(m => m.IdentityCenterName)
                </div>
            </div>
        
            <div class="form-group">
                @Html.LabelFor(m => m.SerialNumber, new { @class = "control-label" })
                <div class="@divCss control-text">
                    @Model.SerialNumber
                    @Html.HiddenFor(m => m.SerialNumber)
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.ValidPeriod, new { @class = "control-label" })
                <div class="@divCss control-text">
                    @Model.ValidPeriod
                    @Html.HiddenFor(m => m.FromDate)
                    @Html.HiddenFor(m => m.ToDate)
                </div>
            </div>
            <div class="form-group">
                <label class="control-label">Статус сертификата</label>
                <div class="@divCss control-text">
                    @EnumHelper.Description(Model.Status())
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.UserRegisterId, new { @class = "control-label required" })
                <div class="@divCss">
                    @if (!Model.IsFromUser)
                    {
                        <div class="input-group">
                            @Html.TextBoxFor( m => m.UserName, new { @class = @inputCss, id = "tbUserFullName"})
                            <span class="input-group-btn">
                                <button id="btnSearch" class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
                            </span>
                        </div>
                        if (Model.UserRegisterId == null)
                        {
                            <div class="help-block">Сретификат выдан: @Model.CertificateUserName</div>     
                        }
                        @Html.ValidationMessageFor(m => m.UserRegisterId)
                    }
                    else
                    {
                        @Html.TextBoxFor(m => m.UserName, new { @class = @inputCss, disabled = "disabled"})
                    }
                    @Html.HiddenFor(m => m.UserRegisterId)
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.SerialNumberEtoken, new { @class = "control-label" })
                <div class="@divCss">
                    @Html.TextBoxFor(m => m.SerialNumberEtoken, new { @class = @inputCss })
                    @Html.ValidationMessageFor(m => m.SerialNumberEtoken)
                </div>
            </div>
            
            <div class="form-group">
                @Html.LabelFor(m => m.PCId, new { @class = "control-label" })
                <div class="@divCss">
                    @Html.DropDownListFor(m => m.PCId, Model.UserPCList, new { @class = @inputCss })
                </div>
            </div>
        
            <div class="form-group">
                @Html.LabelFor(m => m.SelectedInfoSystems, new { @class = "control-label" })
                <div class="@divCss">
                    <div data-bind="template: { name: 'infosystem-template', foreach: InfoSystem }"></div>
                    @Html.ValidationMessageFor(m => m.SelectedInfoSystems)
                    @if(!Model.ReadOnly)
                    {
                        <div class="control-text">
                            <a href="#" data-bind="click: addInfoSystem">Добавить информационную систему</a>
                        </div>
                    }
                </div>
            </div>
            if(!Model.ReadOnly)
            {
            @Html.Partial("_FormActionsPartial")
            }
    }
</div>

<script type="text/html" id="infosystem-template">
    <div class="input-list-item" data-bind="css: { 'input-group': $index() >= 0 }">
        <select class="form-control" name="SelectedInfoSystems[]" data-bind="attr: { name: 'SelectedInfoSystems[' + $index() + ']' }, options: InfoSystemAll, optionsText: 'name', optionsValue: 'id', value: selectedValue"  />
        <span class="input-group-btn" data-bind="">
            <button title="Удалить информационную систему" class="btn btn-default" type="button" data-bind="click: $parent.removeInfoSystem">
                <i class="fa fa-times"></i>
            </button>
        </span>
    </div>
</script>

@section styles
{
    @Styles.Render("~/bundles/jquery-css")
}

@section scripts
{
    <script type="text/javascript" src="@(Url.Content("~/Scripts/AjaxRequest.js"))"></script>    

    <script type="text/javascript">
        $(document).ready(function () {
            @if (Model.ReadOnly)
            {
                @:ReadOnlyView();
            }
            else if(!Model.IsFromUser)
            {
                @:PrepareUserRegisterEdit();
            }

        });

        function SetUserRegister(id, name) {
            $("#UserRegisterId").val(id);
            $("#tbUserFullName").val(name);

            GetPCList();
            GetISList();
        }

        function GetISList() {
            var userId = $("#UserRegisterId").val();
            $.ajax({
                async: false,
                cache: false,
                type: 'POST',
                url: '@Url.Action("InfoSystemList", "UserRegister")',
                data: { userId: userId },
                success: function (result) {
                    koModel.InfoSystem.removeAll();
                    koModel.InfoSystemAll.removeAll();

                    if (result.length > 0) {
                        $.each(result, function (result) {
                            koModel.InfoSystemAll.push({ id: this.Id, name: this.InfoSystemName });
                        });
                    }
                    else {
                    }
                },
                error: handleAjaxError
            });
        }
        
        function SetLastNameFocus() {
            setFocus($("#LastNameFilter"));
        }
    </script>
    <script src="@Url.Content("~/Scripts/knockout-3.2.0.js")"></script>
    <script type="text/javascript">
        function CertRegisterViewModel() {
            var self = this;

            self.InfoSystemAll = ko.observableArray([
                @{
                    if (Model.UserInfoSystems != null)
                    {
                        foreach (var item in Model.UserInfoSystems)
                        {
                            <text>{ id: '@item.Value', name: '@item.Text.Replace("\\", "\\\\")' },</text>
                        }
                    }
                }
            ]);

            self.InfoSystem = ko.observableArray([
                @{
                    if (Model.SelectedInfoSystems != null)
                    {
                        foreach ( var item in Model.SelectedInfoSystems )
                        {
                            <text>{ InfoSystemAll: self.InfoSystemAll, selectedValue: '@item' },</text>
                        }
                    }
                }
            ]);

            self.addInfoSystem = function () {
                self.InfoSystem.push({ InfoSystemAll: self.InfoSystemAll, selectedValue: '-1' });
            };

            self.removeInfoSystem = function () {
                self.InfoSystem.remove(this);
            };
        }

        koModel = new CertRegisterViewModel();
        ko.applyBindings(koModel);
    </script>
  
}